package com.jz.netthings.application.heatseal.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jz.netthings.appengine.baseData.ProviderInfo;
import com.jz.netthings.appengine.mapper.ProviderInfoMapper;
import com.jz.netthings.application.heatseal.bean.*;
import com.jz.netthings.application.heatseal.mapper.mysql.BoxConfigMapper;
import com.jz.netthings.application.heatseal.mapper.mysql.HeatSealMapper;
import com.jz.netthings.application.heatseal.service.HeatSealService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jz.netthings.bean.system.JyCode;
import com.jz.netthings.bean.system.JyUser;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.system.mapper.mysql.JyCodeMapper;
import com.jz.netthings.system.mapper.mysql.JyUserMapper;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 热合表 服务实现类
 * </p>
 *
 * @author lzf
 * @since 2019-03-18
 */
@Service
public class HeatSealServiceImpl extends ServiceImpl<HeatSealMapper, HeatSeal> implements HeatSealService {


    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    HeatSealMapper heatSealMapper;
    @Autowired
    JyUserMapper jyUserMapper;
    @Autowired
    ProviderInfoMapper providerinfoMapper;
    @Autowired
    BoxConfigMapper boxConfigMapper;
    @Autowired
    JyCodeMapper jyCodeMapper;

    @Override
    public Page<HeatSeal> queryAll(Integer currentPage, Integer pageSize) {
        Page<HeatSeal> page = new Page<>(currentPage, pageSize);
        Wrapper<HeatSeal> heatSealWrapper = new EntityWrapper<>();
        heatSealWrapper.like("createTime", AdscmDateUtils.getNowOnlyDateFomat1(new Date()), SqlLike.RIGHT);
        Page<HeatSeal> heatSealPage = super.selectPage(page, null);
        List<HeatSeal> records = heatSealPage.getRecords();
        for (HeatSeal record : records) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getCreateNurse(), null)) {
                record.setCreateNurseName(jyUserMapper.selectById(record.getCreateNurse()).getName());
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getProviderNo(), null)) {
                record.setProvideNoName(providerinfoMapper.selectById(record.getProviderNo()).getName());
            }
        }
        heatSealPage.setTotal(heatSealMapper.selectCount(null));
        return heatSealPage;
    }

    @Override
    public HeatSeal queryByid(String id) throws AdscmSystemException {
//        HeatSeal heatSeal =null;
        if (AdscmBaseUtils.getInstance().isNotEmpty(id, null)) {
            return super.selectById(id);
        } else {
            throw new AdscmSystemException("id为空，不能返回");
        }
    }

    @Override
    public Page<HeatSeal> queryByPNoAndMNo(String pid, String mid, String sTime, Integer currentPage, Integer pageSize, String cid) throws AdscmSystemException {
        Page<HeatSeal> page = new Page<>(currentPage, pageSize);
        boolean isCurrentDay = true;//是否只查询当天的，如果有其他条件的，则不是查询当天
        Wrapper<HeatSeal> wrapper = new EntityWrapper<>();
        if (AdscmBaseUtils.getInstance().isNotEmpty(mid, null)) {
            wrapper.eq("machineNo", mid);
            isCurrentDay = false;
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(pid, null)) {
            wrapper.eq("providerNo", pid);
            isCurrentDay = false;
        }

        if (AdscmBaseUtils.getInstance().isNotEmpty(sTime, null)) {
            wrapper.like("createTime", sTime);
            isCurrentDay = false;
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(cid, null)) {
            wrapper.eq("plasmaNo", cid);
            isCurrentDay = false;
        }
        if (isCurrentDay) {
            wrapper.ge("createTime", AdscmDateUtils.getNowOnlyDateFomat1(new Date()));
        }
        wrapper.orderBy("createTime", false);
        Page<HeatSeal> page1 = super.selectPage(page, wrapper);
        List<HeatSeal> records = page1.getRecords();
        for (HeatSeal record : records) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getCreateNurse(), null)) {
                JyUser jyUser = jyUserMapper.selectById(record.getCreateNurse());
                if (AdscmBaseUtils.getInstance().isNotEmpty(jyUser, null)) {
                    if (AdscmBaseUtils.getInstance().isNotEmpty(jyUser.getName(), null)) {
                        record.setCreateNurseName(jyUser.getName());
                    }
                }
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(record.getProviderNo(), null)) {
                String name = providerinfoMapper.selectById(record.getProviderNo()).getName();
                if (AdscmBaseUtils.getInstance().isNotEmpty(name, null)) {
                    record.setProvideNoName(name);
                }

            }
        }
        page1.setTotal(super.selectCount(wrapper));
        return page1;
    }


    @Override
    public HeatSealData updateHeatSeal(HeatSeal heatSeal, JyUser user) throws AdscmSystemException {
        logger.info("更新血浆入库信息：对应自动扫描入库的");
        if (heatSeal != null){
            HeatSealData data = new HeatSealData();

            if(!AdscmBaseUtils.getInstance().isNotEmpty(heatSeal.getLastWeght(),null)){
                throw new AdscmSystemException("参数错误：热合后重量为 Null");
            }
            if(!AdscmBaseUtils.getInstance().isNotEmpty(heatSeal.getRecheckWeight(),null)){
                throw new AdscmSystemException("参数错误：复核重量为 Null");
            }
            if(!AdscmBaseUtils.getInstance().isNotEmpty(heatSeal.getSealId(),null)){
                throw new AdscmSystemException("参数错误：sealId 为 Null");
            }

            HeatSeal seal = heatSealMapper.selectById(heatSeal.getSealId());
            seal.setLastWeght(heatSeal.getLastWeght());
            seal.setRecheckWeight(heatSeal.getRecheckWeight());

            ProviderInfo providerInfo = providerinfoMapper.selectById(seal.getProviderNo());

            if (providerInfo == null){
                throw new AdscmSystemException("没有查询到浆员基本信息");
            }


            List<BoxConfig> configs = boxConfigMapper.selectList(null);
            BoxConfig config = null;
            if (configs != null && configs.size()>0){
                config = configs.get(0);
            }
            if (config == null){
                throw new AdscmSystemException("配置数据为Null");
            }

            if (AdscmBaseUtils.getInstance().isNotEmpty(seal.getPlasmaNo(),null)){
                //血浆编码不为Null，直接返回
                heatSealMapper.updateById(seal);
            }else{
                //血浆编码为null，先生成血浆编码
                int theYear = AdscmDateUtils.getTheYear(new Date());

                StringBuffer plasmaNo = new StringBuffer();
                String boxNo = null;
                if(!config.getYear().equals(theYear+"")){
                    //证明到新的一年了，就重新开始
                    config.setYear(theYear+"");
                    boxConfigMapper.updateById(config);
                    String yearStr = config.getYear().substring(2,4);
                    plasmaNo.append(config.getMakeCode()).append(yearStr).append("P").append("00000101");
                    boxNo = "000001";
//                    plasmaNo = config.getMakeCode() + yearStr + "P" + "00000001";
                }else{
                    //还是当年，根据标准做递增
                    String maxPlasmaNo = heatSealMapper.getMaxPlasmaNo();
                    String year = maxPlasmaNo.substring(3,5);
                    boxNo = maxPlasmaNo.substring(6,12);
                    String num = maxPlasmaNo.substring(12);

                    Integer boxNum = config.getBoxNum();
                    if(num.equals(boxNum.toString()+"")){
                        //证明箱号得涨了
                        boxNo =  (Integer.valueOf(boxNo) + 1) + "";
                        boxNo =  AdscmBaseUtils.getInstance().addZeroToStr(boxNo,6,"0");
                        num = "01";
                    }else{
                        num =  (Integer.valueOf(num) + 1) + "";
                        num = AdscmBaseUtils.getInstance().addZeroToStr(num,2,"0");
                    }
                    plasmaNo.append(config.getMakeCode()).append(year).append("P").append(boxNo).append(num);
//                    plasmaNo = config.getMakeCode() + year + "P" + boxNo + num;
                }
                seal.setPlasmaNo(plasmaNo.toString());
                seal.setPlasmaScanTime(new Date());
                seal.setEndTime(seal.getPlasmaScanTime());
                seal.setCreateNurse(user.getId()+"");
                seal.setBoxNo(boxNo);
                seal.setMODIFY_TIME(AdscmDateUtils.getDateFomat(seal.getPlasmaScanTime()));
                seal.setSYNDATE(AdscmDateUtils.getNowOnlyDateFomat1(seal.getPlasmaScanTime()));

                heatSealMapper.updateById(seal);
            }
            data.setJzmc(config.getMakeName());
            data.setCardId(providerInfo.getCardId());
            data.setName(providerInfo.getName());
            List<JyCode> codeType = jyCodeMapper.getJyCodeByCodeType("7");
            String sexName = null;
            for (JyCode jyCode : codeType) {
                if(providerInfo.getSex().equals(jyCode.getCode())){
                    sexName = jyCode.getName();
                }
            }
            if (sexName == null){
                sexName = "男";
                if (providerInfo.getSex().equals("2")){
                    sexName = "女";
                }
            }
            data.setSex(sexName);
            codeType = jyCodeMapper.getJyCodeByCodeType("12");
            String bloodType = null;
            for (JyCode jyCode : codeType) {
                if(providerInfo.getBloodType().equals(jyCode.getCode())){
                    bloodType = jyCode.getName();
                }
            }
            if (bloodType == null){
                if (providerInfo.getBloodType().equals("1")){
                    bloodType = "A";
                }else if (providerInfo.getBloodType().equals("2")){
                    bloodType = "B";
                }else if (providerInfo.getBloodType().equals("3")){
                    bloodType = "AB";
                }else if (providerInfo.getBloodType().equals("4")){
                    bloodType = "O";
                }
            }
            data.setBloodType(bloodType);
            data.setXjbh(seal.getPlasmaNo());
            data.setXjType(config.getBloodType());
            data.setXjWeight(seal.getLastWeght());

           return data;
        }else {
            throw new AdscmSystemException("参数错误：Null");
        }
    }

    @Override
    public List<Map<String, String>> getHeatSealBoxByDate(String startDate, String endDate) throws AdscmSystemException {

        logger.info("根据日期【"+startDate+"："+endDate+"】，查询入库的所有血浆箱号");

        String beginTime = startDate +" 00:00:00";
        String endTime = endDate +" 23:59:59";

        return heatSealMapper.getHeatSealBoxByDate(beginTime, endTime);
    }

    @Value("${jz.unitName}")
    private String unitName;
    @Value("${jz.print.xjzyd}")
    private String xjzyd;

    @Override
    public PlasmaStockPrintSupport getStockByBox(String boxCode) throws AdscmSystemException {

        logger.info("根据箱号【"+boxCode+"】，查询入库记录");

        if (!AdscmBaseUtils.getInstance().isNotEmpty(boxCode,null)){
            throw new AdscmSystemException("箱号为null，查询失败");
        }

        PlasmaStockPrintSupport psps = new PlasmaStockPrintSupport();
        psps.setFormHeader(unitName + xjzyd);
        psps.setBoxNum(boxCode);
        psps.setBoxType("普通");
        Map<String, String> heatByBox = heatSealMapper.getHeatByBox(boxCode);
        if (heatByBox != null){
            psps.setSumStockNum(heatByBox.get("sumStockNum"));
            psps.setSumPlasmaWeight(heatByBox.get("sumPlasmaWeight"));
        }


        List<JyCode> assayResult = jyCodeMapper.getJyCodeByCodeType("inspectionResult");//化检结果，阴性/阳性
        Map<String ,JyCode> assayMap = new HashMap<>();
        for (JyCode jyCode : assayResult) {
            assayMap.put(jyCode.getCode(),jyCode);
        }
        List<JyCode> altResult = jyCodeMapper.getJyCodeByCodeType("ALTResult");//
        Map<String ,JyCode> altMap = new HashMap<>();
        for (JyCode jyCode : altResult) {
            altMap.put(jyCode.getCode(),jyCode);
        }
        List<PlasmaStock> plasmaStockList = heatSealMapper.getPlasmaInfoBox(boxCode);

        if (plasmaStockList != null && plasmaStockList.size()>0){
            for (PlasmaStock arl : plasmaStockList) {

                ////////////////////////////////////////
                String hbsag = arl.getHbsag();
                if(AdscmBaseUtils.getInstance().isNotEmpty(hbsag,null)){
                    JyCode code = assayMap.get(hbsag);
                    if (code != null) {
                        arl.setHbsag(code.getName());
                    }
                }
                ////////////////////////////////////////
                String hcv = arl.getHcv();
                if(AdscmBaseUtils.getInstance().isNotEmpty(hcv,null)){
                    JyCode code = assayMap.get(hcv);
                    if (code != null) {
                        arl.setHcv(code.getName());
                    }
                }
                ////////////////////////////////////////
                String hiv = arl.getHiv();
                if(AdscmBaseUtils.getInstance().isNotEmpty(hiv,null)){
                    JyCode code = assayMap.get(hiv);
                    if (code != null) {
                        arl.setHiv(code.getName());
                    }
                }
                ////////////////////////////////////////
                String syphilis = arl.getSyphilis();
                if(AdscmBaseUtils.getInstance().isNotEmpty(syphilis,null)){
                    JyCode code = assayMap.get(syphilis);
                    if (code != null) {
                        arl.setSyphilis(code.getName());
                    }
                }
                ////////////////////////////////////////
                String alt = arl.getAlt();
                if(AdscmBaseUtils.getInstance().isNotEmpty(alt,null)){
                    JyCode code = altMap.get(alt);
                    if (code != null){
                        arl.setAlt(code.getName());
                    }
                }
                ////////////////////////////////////////
                String qxbz = arl.getQxbz();
                if(AdscmBaseUtils.getInstance().isNotEmpty(qxbz,null)){
                    if ("1".equals(qxbz)){
                        arl.setQxbz("合格");
                    }else{
                        arl.setQxbz("不合格");
                    }
                }
                ////////////////////////////////////////
                String checkResult = arl.getCheckResult();
                if(AdscmBaseUtils.getInstance().isNotEmpty(checkResult,null)){
                    if ("1".equals(checkResult)){
                        arl.setCheckResult("合格");
                    }else{
                        arl.setCheckResult("不合格");
                    }
                }

            }
        }


        psps.setPlasmaStockList(plasmaStockList);


        return psps;
    }
}
